import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Profile } from './entities/profile.entity';
import { Image } from './entities/image.entity';
import { PersonalList } from './entities/personal-list.entity';

@Injectable()
export class PersonalService {
  constructor(
    @InjectRepository(Profile) private profileRepo: Repository<Profile>,
    @InjectRepository(Image) private imageRepo: Repository<Image>,
    @InjectRepository(PersonalList) private personalListRepo: Repository<PersonalList>,
  ) { }

  // -------------------------- 个人信息（Profile）CRUD --------------------------
  async createProfile(data: Partial<Profile>): Promise<Profile> {
    // 代码层面设置默认值：如果未传递 skills，则默认为空数组
    const profile = this.profileRepo.create({
      ...data,
      skills: data.skills ?? [], // 关键：用空数组兜底
    });
    return this.profileRepo.save(profile);
  }

  async getProfiles(): Promise<Profile[]> {
    return this.profileRepo.find();
  }

  async getProfileById(id: number): Promise<Profile> {
    const profile = await this.profileRepo.findOneBy({ id });
    if (!profile) throw new NotFoundException('Profile not found');
    return profile;
  }

  async updateProfile(id: number, data: Partial<Profile>): Promise<Profile> {
    await this.profileRepo.update(id, data);
    return this.getProfileById(id);
  }

  async deleteProfile(id: number): Promise<void> {
    const result = await this.profileRepo.delete(id);
    if (result.affected === 0) throw new NotFoundException('Profile not found');
  }

  // 单独更新头像
  async updateAvatar(id: number, avatarUrl: string): Promise<Profile> {
    return this.updateProfile(id, { avatar: avatarUrl });
  }

  // -------------------------- 图片资源（Image）CRUD --------------------------
  async createImage(data: Partial<Image>): Promise<Image> {
    const image = this.imageRepo.create(data);
    return this.imageRepo.save(image);
  }

  async getImages(): Promise<Image[]> {
    return this.imageRepo.find();
  }

  async getImageById(id: number): Promise<Image> {
    const image = await this.imageRepo.findOneBy({ id });
    if (!image) throw new NotFoundException('Image not found');
    return image;
  }

  async updateImage(id: number, data: Partial<Image>): Promise<Image> {
    await this.imageRepo.update(id, data);
    return this.getImageById(id);
  }

  async deleteImage(id: number): Promise<void> {
    const result = await this.imageRepo.delete(id);
    if (result.affected === 0) throw new NotFoundException('Image not found');
  }

  // -------------------------- 图文内容（Post）CRUD --------------------------
  async createPost(data: Partial<PersonalList>): Promise<PersonalList> {
    data.sort_order = data.sort_order || 1; // 默认排序权重为1
    const post = this.personalListRepo.create(data);
    return this.personalListRepo.save(post);
  }

  async getPosts(): Promise<PersonalList[]> {
    return this.personalListRepo.find({
      order: {
        sort_order: 'DESC', // 数字越大越靠前（降序排列）
        createdAt: 'DESC'
      },
    });
  }

  async getPostById(id: number): Promise<PersonalList> {
    const post = await this.personalListRepo.findOneBy({ id });
    if (!post) throw new NotFoundException('Post not found');
    return post;
  }

  async updatePost(id: number, data: Partial<PersonalList>): Promise<PersonalList> {
    await this.personalListRepo.update(id, data);
    return this.getPostById(id);
  }

  async deletePost(id: number): Promise<void> {
    const result = await this.personalListRepo.delete(id);
    if (result.affected === 0) throw new NotFoundException('Post not found');
  }
}
